package com.enjoy.rpc.common;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务注册
 * Created by HP on 2019/7/3.
 */
public class ServerUtils {
    public static boolean register(ConcurrentHashMap<String, List<String>> serverList, String serverInfo) {
        String[] infos = serverInfo.split(";");//格式：127.0.0.1:8080
        if (serverList.containsKey(infos[0])) {
            serverList.get(infos[0]).add(infos[1]);
        } else {
            serverList.put(infos[0], new ArrayList<String>(Arrays.asList(infos[1])));
        }
        return true;
    }

    public static String find(ConcurrentHashMap<String, List<String>> serverList, String serverName) {
        List<String> addrs = serverList.get(serverName);
        //随机返回一个地址
        if (addrs != null && addrs.size() > 0) {
            for (String addr : addrs) {
                System.out.println("已注册服务：" + serverName + "***" + addr);
            }
            Object[] res = addrs.toArray();
            Random random = new Random();
            return res[random.nextInt(res.length)].toString();
        }
        return null;
    }
}
